import { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { message } from 'antd';
import { loginIn, selectRouter_permission } from '../redux/Slice/userSlice';
import axios from 'axios';
import config from '../Config';
import Config from '../Config';
const UserInit = () => {
  const [isLoading, setIsLoading] = useState(true);
  const dispatch = useDispatch();

  useEffect(() => {
    const fetchUser = async () => {
      setIsLoading(true);
      await axios
        .get(config.baseURL + '/user/autologin')
        .then(function (response) {
          let resData = response.data.data;
          console.log(resData);
          if (response.data.code === 1) {
            dispatch(loginIn(resData));
            setIsLoading(false);
            message.success('自动登录成功', 1);
          }
          if (response.data.code === 10000) {
            setIsLoading(false);
            message.info('欢迎！请登录或注册', 1);
          }
        })
        .catch(function (error) {
          console.log(error);
          setIsLoading(false);
          message.info('欢迎！请登录或注册', 1);
        });
    };
    if (config.isDev) setIsLoading(false);
    else fetchUser();
  }, []);

  return { isLoading };
};

const UserAuth = routerName => {
  const [authority, SetAuthority] = useState(false);
  let router_permission = useSelector(selectRouter_permission);
  useEffect(() => {
    let index;
    if (Config.isDev) {
      SetAuthority(true);
    } else if (router_permission != null) {
      index = router_permission.indexOf(routerName);
      if (index >= 0) SetAuthority(true);
      else SetAuthority(false);
    }
  }, [router_permission]);

  return { authority };
};

const RolePermission = fresh => {
  const [isLoading, setIsLoading] = useState(true);
  const [data, SetData] = useState([]);
  const [routeList, SetRouteList] = useState([]);
  const [apiList, SetApiList] = useState([]);
  useEffect(() => {
    const fetch = async () => {
      setIsLoading(true);
      await axios
        .get(config.baseURL + '/role/permissionlist')
        .then(function (response) {
          let resData = response.data.data;
          console.log(resData);
          if (response.data.code === 1) {
            SetData(resData);
          }
          if (response.data.code >= 10000) {
            message.info('获取角色权限信息失败', 1);
          }
        })
        .catch(function (error) {
          console.log(error);

          message.info('获取角色权限信息失败', 1);
        });

      await axios
        .get(config.baseURL + '/role/routeApiList')
        .then(function (response) {
          let resData = response.data.data;
          console.log(resData);
          if (response.data.code === 1) {
            SetApiList(resData.api);
            SetRouteList(resData.route);
            setIsLoading(false);
          }
          if (response.data.code >= 10000) {
            setIsLoading(false);
            message.info('获取路由权限信息失败', 1);
          }
        })
        .catch(function (error) {
          console.log(error);
          setIsLoading(false);
          message.info('获取路由权限信息失败', 1);
        });
    };
    fetch();
  }, [fresh]);

  return { isLoading, data, apiList, routeList, SetRouteList, SetApiList, SetData };
};
const StringToArray = str => {
  let arr = str.trim().split(/\s+/);
  if (arr == '') return [];
  return arr.map(val => {
    return parseInt(val);
  });
};
const GetCasterDepartment = (value, refresh) => {
  const [departmentList, SetdepartmentList] = useState([]);
  const [departmentOriginList, setdepartmentOriginList] = useState([]);
  let umap = new Map();
  const dfs = (node, data) => {
    let index = umap.get(node.value);
    if (data[index].departmentType === 1) return;

    let children = StringToArray(data[index].departmentChildren);
    if (children.length == 0) return;
    node.children = [];
    for (let i = 0; i < children.length; i++) {
      let temp = {
        value: data[umap.get(children[i])].departmentId,
        label: data[umap.get(children[i])].departmentName,
      };
      node.children.push(temp);
      dfs(temp, data);
    }
  };
  const departmentTrans = data => {
    let root = [];
    for (let i = 0; i < data.length; i++) {
      umap.set(data[i].departmentId, i);
      if (data[i].departmentParent == -1) root.push(i);
    }
    let ans = [];
    for (let k = 0; k < root.length; k++) {
      let res = {};
      res.value = data[root[k]].departmentId;
      res.label = data[root[k]].departmentName;
      let children = StringToArray(data[root[k]].departmentChildren);
      res.children = [];
      for (let i = 0; i < children.length; i++) {
        let temp = {
          value: data[umap.get(children[i])].departmentId,
          label: data[umap.get(children[i])].departmentName,
        };
        res.children.push(temp);
        dfs(temp, data);
      }
      ans.push(res);
    }
    if (value != undefined || value != null) ans.push(value);
    return ans;
  };
  useEffect(() => {
    const fetch = async () => {
      await axios
        .get(config.baseURL + '/user/department')
        .then(response => {
          let res = response.data;
          if (res.code === 1) {
            setdepartmentOriginList(res.data);
            let data = departmentTrans(res.data);
            SetdepartmentList(data);
          } else if (res.code >= 10000) {
            message.error('获取部门列表出错，请联系后台', 1);
          }
        })
        .catch(error => {
          console.log(error);
          message.error('获取部门列表出错，请联系后台', 1);
        });
    };
    fetch();
  }, [refresh]);

  return { departmentList, SetdepartmentList, departmentOriginList };
};
const GetCasterPlace = (value, refresh) => {
  const [placeList, SetplaceList] = useState([]);
  const [placeOriginList, setplaceOriginList] = useState([]);
  let umap = new Map();
  const dfs = (node, data) => {
    let index = umap.get(node.value);
    if (data[index].placeType === 1) return;

    let children = StringToArray(data[index].placeChildren);
    if (children.length == 0) return;
    node.children = [];
    for (let i = 0; i < children.length; i++) {
      let temp = {
        value: data[umap.get(children[i])].placeId,
        label: data[umap.get(children[i])].placeName,
      };
      node.children.push(temp);
      dfs(temp, data);
    }
  };
  const placeTrans = data => {
    let root = [];
    for (let i = 0; i < data.length; i++) {
      umap.set(data[i].placeId, i);
      if (data[i].placeParent == -1) root.push(i);
    }
    let ans = [];
    for (let k = 0; k < root.length; k++) {
      let res = {};
      res.value = data[root[k]].placeId;
      res.label = data[root[k]].placeName;
      let children = StringToArray(data[root[k]].placeChildren);
      res.children = [];
      for (let i = 0; i < children.length; i++) {
        let temp = {
          value: data[umap.get(children[i])].placeId,
          label: data[umap.get(children[i])].placeName,
        };
        res.children.push(temp);
        dfs(temp, data);
      }
      ans.push(res);
    }
    if (value != undefined || value != null) ans.push(value);
    return ans;
  };
  useEffect(() => {
    const fetch = async () => {
      await axios
        .get(config.baseURL + '/place/allplace')
        .then(response => {
          let res = response.data;
          if (res.code === 1) {
            console.log(res.data);
            setplaceOriginList(res.data);
            let data = placeTrans(res.data);
            SetplaceList(data);
          } else if (res.code >= 10000) {
            message.error('获取存放地列表出错，请联系后台', 2);
          }
        })
        .catch(error => {
          console.log(error);
          message.error('获取存放地列表出错，请联系后台', 2);
        });
    };
    fetch();
  }, [refresh]);
  return { placeList, SetplaceList, placeOriginList };
};
export { UserInit, UserAuth, RolePermission, GetCasterDepartment, GetCasterPlace };
